package org.zzul.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
@Component
public class ZuulClientFilter extends ZuulFilter{
    @Autowired
    private RedisTemplate redisTemplate; 
	
	@Override
	public Object run() {
	      //获取上下文
        RequestContext requestContext =  RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest  request = requestContext.getRequest();
        //获取请求路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        //用户正在登陆。。。放行
        if(uri.indexOf("/selectLogin")==-1){
            //获取请求token
            String token = request.getHeader("token");
            System.out.println("token:"+token);
            //token有效。。。放行
            if(token != null && redisTemplate.opsForValue().get(token)!=null){
                System.out.println("当前登录用户："+redisTemplate.opsForValue().get(token));
            }else {
              //设置401错误码(没有访问权限)
                System.out.println(HttpStatus.UNAUTHORIZED+"<============================");
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                //不允许继续访问其它过滤器和控制器
                requestContext.setSendZuulResponse(false);
                
            }
        }
        return null;
	}

	@Override
	public boolean shouldFilter() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public String filterType() {
		// TODO Auto-generated method stub
//		FilterConstants.PRE_TYPE
		return "pre";
	}

}
